package cn.wolfcode.service.impl;


import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    //============ 删除操作：删除角色后要删除关系表的数据 ===============
    @Override
    public void delete(Long id) {
        // 删除角色表中的数据
        roleMapper.deleteByPrimaryKey(id);
        // 删除 关系表的数据
        roleMapper.deleteRelationById(id);

    }



    @Override
    public Role selectOne(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Override
    public List<Role> selectAll() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }

    // =============新增角色，关系表也需要添加数据=============
    @Override
    public void insert(Role role, Long[] permissionIds) {
        // 添加角色
        roleMapper.insert(role);

        // =====添加 角色-权限表 数据==== 注意点： 循环添加 =====
        if (permissionIds != null && permissionIds.length > 0){
            for (Long permissionId : permissionIds) {

                roleMapper.saveRelation(role.getId(), permissionId);
            }
        }
    }

    //==========修改==========
    @Override
    public void update(Role role, Long[] permissionIds) {
        // 修改角色表
        roleMapper.updateByPrimaryKey(role);

        // ==== 修改前 先 删除关系表数据  ====
        roleMapper.deleteRelationById(role.getId());
        // 删除后再插入
        if (permissionIds != null && permissionIds.length > 0) {
            for (Long permissionId : permissionIds) {
                roleMapper.saveRelation(role.getId(), permissionId);
            }
        }
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        // 表明接下来的查询用分页
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = roleMapper.selectForList(qo);
        return new PageInfo<>(roles);

        /*int count = roleMapper.selectForCount(qo);
        if (count == 0){
            return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), 0, Collections.emptyList());
        }
        return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), count, roleMapper.selectForList(qo));
*/
    }

    @Override
    public List<Role> selectRolesById(Long id) {

        return roleMapper.selectRolesById(id);
    }
}
